# api/v1/asr_engine.py

from fastapi import APIRouter, HTTPException, Depends
from typing import Dict, Any, Optional
from pydantic import BaseModel
import logging

from core.asr_engine import asr_engine
from core.config import settings
from core.paraformer_engine import is_funasr_available, get_funasr_installation_guide

logger = logging.getLogger(__name__)

router = APIRouter()


class EngineInfo(BaseModel):
    """引擎信息模型"""
    name: str
    type: str
    is_ready: bool
    supported_languages: Dict[str, Any]
    model_info: Optional[Dict[str, Any]] = None


class EngineStatus(BaseModel):
    """引擎状态模型"""
    current_engine: str
    available_engines: list
    is_ready: bool
    engine_info: EngineInfo


@router.get("/status", response_model=EngineStatus)
async def get_engine_status():
    """获取当前 ASR 引擎状态"""
    try:
        # 获取当前引擎信息
        engine_name = type(asr_engine).__name__
        engine_type = settings.ASR_ENGINE
        
        # 获取支持的语言
        supported_langs = asr_engine.get_supported_languages()
        
        # 获取模型信息（如果支持）
        model_info = None
        if hasattr(asr_engine, 'get_model_info'):
            model_info = asr_engine.get_model_info()
        
        # 检查可用的引擎
        available_engines = ["whisper"]
        if is_funasr_available():
            available_engines.append("paraformer")
        
        engine_info = EngineInfo(
            name=engine_name,
            type=engine_type,
            is_ready=asr_engine.is_ready(),
            supported_languages=supported_langs,
            model_info=model_info
        )
        
        return EngineStatus(
            current_engine=engine_type,
            available_engines=available_engines,
            is_ready=asr_engine.is_ready(),
            engine_info=engine_info
        )
        
    except Exception as e:
        logger.error(f"获取引擎状态失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取引擎状态失败: {str(e)}")


@router.get("/engines")
async def get_available_engines():
    """获取可用的 ASR 引擎列表"""
    engines = [
        {
            "name": "whisper",
            "display_name": "Whisper ASR",
            "description": "基于 OpenAI Whisper 的多语言语音识别",
            "supported_languages": ["auto", "zh", "en", "ja", "ko", "fr", "es", "ru", "de"],
            "features": ["多语言支持", "自动语言检测", "翻译功能"],
            "available": True
        }
    ]
    
    # 检查 Paraformer 是否可用
    if is_funasr_available():
        engines.append({
            "name": "paraformer",
            "display_name": "Paraformer ASR",
            "description": "基于 FunASR 的中文语音识别模型",
            "supported_languages": ["zh"],
            "features": ["中文优化", "高精度识别", "实时处理"],
            "available": True
        })
    else:
        engines.append({
            "name": "paraformer",
            "display_name": "Paraformer ASR",
            "description": "基于 FunASR 的中文语音识别模型（需要安装 FunASR）",
            "supported_languages": ["zh"],
            "features": ["中文优化", "高精度识别", "实时处理"],
            "available": False,
            "installation_guide": get_funasr_installation_guide()
        })
    
    return {
        "engines": engines,
        "current_engine": settings.ASR_ENGINE
    }


@router.get("/test")
async def test_engine():
    """测试当前 ASR 引擎"""
    try:
        if not asr_engine.is_ready():
            raise HTTPException(status_code=503, detail="ASR 引擎未就绪")
        
        # 使用测试音频文件
        test_audio_path = settings.BASE_DIR / "test_speech_4.wav"
        
        if not test_audio_path.exists():
            return {
                "status": "success",
                "message": "引擎就绪，但测试音频文件不存在",
                "test_audio_path": str(test_audio_path)
            }
        
        # 执行测试识别
        result = asr_engine.transcribe(
            audio_path=test_audio_path,
            language="zh",
            task="transcribe",
            return_segments=False
        )
        
        return {
            "status": "success",
            "message": "引擎测试成功",
            "test_result": {
                "text": result.get("text", ""),
                "detected_language": result.get("detected_language", ""),
                "duration": result.get("duration", 0),
                "model": result.get("model", "")
            }
        }
        
    except Exception as e:
        logger.error(f"引擎测试失败: {e}")
        raise HTTPException(status_code=500, detail=f"引擎测试失败: {str(e)}")


@router.get("/config")
async def get_engine_config():
    """获取当前引擎配置"""
    return {
        "asr_engine": settings.ASR_ENGINE,
        "use_real_asr": settings.USE_REAL_ASR,
        "device": settings.ASR_DEVICE,
        "sample_rate": settings.ASR_SAMPLE_RATE,
        "paraformer_config": {
            "model_path": str(settings.PARAFORMER_MODEL_PATH),
            "device": settings.PARAFORMER_DEVICE,
            "config_path": str(settings.PARAFORMER_CONFIG_PATH)
        } if settings.ASR_ENGINE == "paraformer" else None
    }
